package com.lin.nio.channel.threads;

import com.lin.nio.utils.ByteBufferUtil;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Random;

/**
 * Boss线程
 * 接收所有的客户端连接，创建子线程来处理客户端的读写事件。
 */
@Slf4j
public class BossServer {
    public static void main(String[] args) throws IOException {

        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(1122));

        Selector selector = Selector.open();
        SelectionKey sscKey = ssc.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println(sscKey);

        // 创建一定数量的worker
        Random random = new Random();
        WorkerServer[] workers = new WorkerServer[6];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new WorkerServer("worker-" + i);
        }
        while (true) {
            selector.select();

            Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();

                SocketChannel sc = ssc.accept();// 接受客户端的连接
                log.info("connected...");

                // 随机分配给worker
                WorkerServer worker = workers[random.nextInt(6)];
                worker.register(sc);

                // 处理过的key要清除掉
                iter.remove();

            }

        }
    }
}
